package com.css.dzj.dzjap.modules.executorinfo.service.impl;

import com.css.dzj.dzjap.common.util.Constant;
import com.css.dzj.dzjap.common.util.R;
import com.css.dzj.dzjap.common.util.ServiceUtil;
import com.css.dzj.dzjap.modules.executorinfo.dao.ExecutorInfoDao;
import com.css.dzj.dzjap.modules.executorinfo.entity.ApExecutorInfoEntity;
import com.css.dzj.dzjap.modules.executorinfo.entity.QApExecutorInfoEntity;
import com.css.dzj.dzjap.modules.executorinfo.service.ExecutorInfoService;
import com.css.dzj.dzjap.sys.user.entity.LoginUser;
import com.querydsl.core.QueryResults;
import com.querydsl.core.types.ExpressionUtils;
import com.querydsl.core.types.Predicate;
import com.querydsl.jpa.impl.JPAQueryFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 执法人员信息service实现
 */
@Service
public class ExecutorInfoServiceImpl implements ExecutorInfoService {
    @Autowired
    private ExecutorInfoDao executorInfoDao;

    //注入JPAQueryFactory工厂
    @Autowired
    JPAQueryFactory jpaQueryFactory;
    @Autowired
    private ServiceUtil serviceUtil;

    /**
     * 分页查询执法人员信息
     * @param pageRequest
     * @return
     */
    @Override
    public QueryResults<ApExecutorInfoEntity> getAllExecutorInfo(PageRequest pageRequest) {
        QApExecutorInfoEntity qExecutor = QApExecutorInfoEntity.apExecutorInfoEntity;
        Predicate predicate = qExecutor.isNotNull().or(qExecutor.isNull());
        //查询条件：删除标记为 0 未删除的
        predicate = ExpressionUtils.and(predicate,qExecutor.executorDelFlag.eq("0"));
        return jpaQueryFactory
                .selectFrom(qExecutor)
                .where( predicate )
                //根据创建时间倒叙排序
                .orderBy(qExecutor.executorCreateTime.desc())
                .offset(pageRequest.getOffset())
                .limit(pageRequest.getPageSize())
                .fetchResults();
    }

    /**
     * 对外接口查询所有的执法人员
     * @return
     */
    @Override
    public List<ApExecutorInfoEntity> selectAll() {
        List<ApExecutorInfoEntity> list = executorInfoDao.findAll();
        QApExecutorInfoEntity qExecutor = QApExecutorInfoEntity.apExecutorInfoEntity;
        Predicate predicate = qExecutor.isNotNull().or(qExecutor.isNull());
        //查询条件：删除标记为 0 未删除的
        predicate = ExpressionUtils.and(predicate,qExecutor.executorDelFlag.eq("0"));
        return jpaQueryFactory
                .selectFrom(qExecutor)
                .where(predicate)
                .orderBy(qExecutor.executorCreateTime.desc())
                .fetch();
    }

    /**
     * 对外接口多调节查询
     * @param executorName
     * @param executorCharacter
     * @param executorArea
     * @param executorCategory
     * @return
     */
    @Override
    public List<ApExecutorInfoEntity> getSelectInfo(String executorName, String executorCharacter, String executorArea, String executorCategory) {
        QApExecutorInfoEntity qExecutor = QApExecutorInfoEntity.apExecutorInfoEntity;
        Predicate predicate = qExecutor.isNotNull().or(qExecutor.isNull());
        predicate = ("".equals(executorArea) || executorArea == null) ? predicate : ExpressionUtils.and(predicate, qExecutor.executorArea.like("%"+executorArea+"%"));
        predicate = ("".equals(executorCategory) || executorCategory == null) ? predicate : ExpressionUtils.and(predicate, qExecutor.executorCategory.like("%"+executorCategory+"%"));
        predicate = ("".equals(executorCharacter) || executorCharacter == null) ? predicate : ExpressionUtils.and(predicate, qExecutor.executorCharacter.eq(executorCharacter));
        predicate = ("".equals(executorName) || executorName == null) ? predicate : ExpressionUtils.and(predicate, qExecutor.executorName.like("%"+executorName+"%"));
        predicate = ExpressionUtils.and(predicate, qExecutor.executorDelFlag.eq("0")) ;

        return jpaQueryFactory
                .selectFrom(qExecutor)
                .where( predicate )
                .orderBy(qExecutor.executorCreateTime.desc())
                .fetch();
    }

    @Override
    public List<ApExecutorInfoEntity> getIds(List<String> ids) {
        List<ApExecutorInfoEntity> list = new ArrayList<>();
        for (int i = 0; i <ids.size() ; i++) {
            ApExecutorInfoEntity apExecutorInfoEntity =  executorInfoDao.findById(ids.get(i)).get();
            list.add(apExecutorInfoEntity);
        }
        return list;
    }

    /**
     * 通过ID查询执法人员信息
     * @param id 执法人员ID
     * @return
     */
    @Override
    public ApExecutorInfoEntity getExecutorInfo(String id) {
        if (StringUtils.isEmpty(id)){
            throw new RuntimeException("参数为空");
        }
        QApExecutorInfoEntity qExecutor = QApExecutorInfoEntity.apExecutorInfoEntity;
        return jpaQueryFactory
                .selectFrom(qExecutor)
                .where(
                        qExecutor.id.eq(id),
                        qExecutor.executorDelFlag.eq("0"))
                .fetchOne();
    }

    /**
     * 新增执法人员信息
     * @param executorInfo
     * @return
     */
    @Override
    @Transactional
    public String addExecutorInfo(ApExecutorInfoEntity executorInfo) {
        executorInfo.setExecutorDelFlag("0");
        executorInfo.setExecutorCreateTime(new Date());
        executorInfo.setExecutorUpdateTime(new Date());
        executorInfoDao.save(executorInfo);
        return executorInfo.getId();

    }

    /**
     * 根据ID逻辑删除执法人员信息
     * @param executorid 执法人员信息ID
     * @return
     */
    @Override
    @Transactional
    public boolean delExecutorInfo(String executorid) {
        QApExecutorInfoEntity qExecutor = QApExecutorInfoEntity.apExecutorInfoEntity;
        if (StringUtils.isEmpty(executorid)){
            return false;
        }
        try{
            jpaQueryFactory
                    .update(qExecutor)
                    //逻辑删除执法人员信息，只需改变删除状态即可 0未删除 1已删除
                    .set(qExecutor.executorDelFlag,"1")
                    //更新修改时间
                    .set(qExecutor.executorUpdateTime,new Date())
                    .where(
                            qExecutor.id.eq(executorid),
                            qExecutor.executorDelFlag.eq("0"))
                    .execute();
            return true;
        }catch (Exception e){
            return false;
        }
    }

    /**
     * 修改执法人员信息
     * @param executorInfo
     * @return
     */
    @Override
    @Transactional
    public void updExecutorInfo( ApExecutorInfoEntity executorInfo) {

    }

    /**
     * 根据执法人员等级分页查询执法人员信息
     * @param executorLevel
     * @return
     */
    @Override
    public QueryResults<ApExecutorInfoEntity> findExecutorByLevel(String executorLevel, PageRequest pageRequest) {
        QApExecutorInfoEntity qExecutor = QApExecutorInfoEntity.apExecutorInfoEntity;
        Predicate predicate = qExecutor.isNotNull().or(qExecutor.isNull());
        //查询条件：删除标记为 0 未删除的
        predicate = ExpressionUtils.and(predicate,qExecutor.executorDelFlag.eq("0"));

        return jpaQueryFactory
                .selectFrom(qExecutor)
                .where( predicate,
                        //根据执法人员等级分页查询执法人员信息
                        qExecutor.executorLevel.eq(executorLevel)
                )
                //根据创建时间倒叙排序
                .orderBy(qExecutor.executorCreateTime.desc())
                .offset(pageRequest.getOffset())
                .limit(pageRequest.getPageSize())
                .fetchResults();
    }


    /**
     * 根据执法人员等级查询执法人员信息
     * @param executorLevel
     * @return
     */
    @Override
    public List<ApExecutorInfoEntity> findExecutorByExecutorLevel(String executorLevel, HttpServletRequest request) {
        /**
         * 获取suser
         */
        R r = serviceUtil.getUserInfoByRequest(request);
        String suserName = "";
        String location = "";
        if(r.getCode().equals("200")){
            LoginUser userInfo =  (LoginUser)r.get("data");
            /**
             * 获取用户名
             */
            suserName =userInfo.getLoginName();
            /**
             * 获取用户的省份
             */
            String orgName = userInfo.getOrgName();
            location = orgName.substring(0,orgName.indexOf("地震局"));
        }
        QApExecutorInfoEntity qApExecutorInfoEntity = QApExecutorInfoEntity.apExecutorInfoEntity;

        if (Constant.STATE_LEVEL.equals(executorLevel)){
            /**
             * 如果是国家级
             */
            return jpaQueryFactory.selectFrom(qApExecutorInfoEntity).where(qApExecutorInfoEntity.executorLocation.like("%"+location+"%"),
                    qApExecutorInfoEntity.executorDelFlag.eq(Constant.NO_DELETE)).fetch();

        }else {
            return jpaQueryFactory.selectFrom(qApExecutorInfoEntity).where(qApExecutorInfoEntity.executorLocation.notLike("%"+location+"%"),
                    qApExecutorInfoEntity.executorDelFlag.eq(Constant.NO_DELETE)).fetch();
        }
    }

    /**
     * 多条件分页查询执法人员信息
     * @param pageable
     * @param executorName 姓名
     * @param executorCode 执法证号
     * @param executorOrganization 所属主体全称
     * @param executorLevel 职级
     * @param executorCharacter 性质
     * @return
     */
    @Override
    public QueryResults<ApExecutorInfoEntity> getListExecutorInfo(Pageable pageable, String executorName, String executorCode, String executorOrganization,  String executorLevel,String executorCharacter) {
        QApExecutorInfoEntity qExecutor = QApExecutorInfoEntity.apExecutorInfoEntity;
        Predicate predicate = qExecutor.isNotNull().or(qExecutor.isNull());
        predicate = ("".equals(executorCode) || executorCode == null) ? predicate : ExpressionUtils.and(predicate, qExecutor.executorCode.like("%"+executorCode+"%"));
        predicate = ("".equals(executorOrganization) || executorOrganization == null) ? predicate : ExpressionUtils.and(predicate, qExecutor.executorOrganization.like("%"+executorOrganization+"%"));
        predicate = ("".equals(executorLevel) || executorLevel == null) ? predicate : ExpressionUtils.and(predicate, qExecutor.executorLevel.eq(executorLevel));
        predicate = ("".equals(executorCharacter) || executorCharacter == null) ? predicate : ExpressionUtils.and(predicate, qExecutor.executorCharacter.eq(executorCharacter));
        predicate = ("".equals(executorName) || executorName == null) ? predicate : ExpressionUtils.and(predicate, qExecutor.executorName.like("%"+executorName+"%"));
        predicate = ExpressionUtils.and(predicate, qExecutor.executorDelFlag.eq("0")) ;

        return jpaQueryFactory
                .selectFrom(qExecutor)
                .where( predicate )
                .orderBy(qExecutor.executorCreateTime.desc())
                .offset(pageable.getOffset())//起始页
                .limit(pageable.getPageSize())//每页大小
                .fetchResults();
    }

    @Override
    public List<ApExecutorInfoEntity> getApList() {

        QApExecutorInfoEntity q = QApExecutorInfoEntity.apExecutorInfoEntity;
        Predicate predicate = q.isNotNull().or(q.isNull());
        predicate = ExpressionUtils.and(predicate, q.executorDelFlag.eq(Constant.NO_DELETE));
        return jpaQueryFactory.selectFrom(q).where(predicate).fetch();
    }

}
